package priv.wjh.concurrent.tools.timer;

/**
 * //TODO
 *
 * @author wangjunhao
 **/
public class WheelTimer {
    private final WheelTimerBuckets buckets;
    private final long tickDuration;


    public WheelTimer(int size, long tickDuration) {
        this.buckets = new WheelTimerBuckets(size);
        this.tickDuration = tickDuration;
    }

    public void addTask(long delay, Runnable runnable){
        int times = (int) (delay / tickDuration);
        int i = (int) (delay % tickDuration);
        buckets.add(i, times, delay, runnable);
    }


    private static class WheelTimerBuckets{
        private final int size;
        private final int mask;
        private volatile int index;
        private final WheelTimerBucket[] buckets;

        private WheelTimerBuckets(int size) {
            this.size = size;
            this.mask = size - 1;
            this.index = 0;
            this.buckets = new WheelTimerBucket[size];
        }

        public void add(int i, int times, long delay, Runnable runnable){
            buckets[index + i + 1].add(times, delay, runnable);
        }
    }


    private static class WheelTimerBucket{
        private volatile WheelTimerNode head;
        private volatile WheelTimerNode tail;

        public WheelTimerBucket() {
            head = tail = null;
        }

        public void add(int times, long delay, Runnable runnable) {
            WheelTimerNode wheelTimerNode = new WheelTimerNode(times, delay, runnable);

        }


    }

    private static class WheelTimerNode{
        private WheelTimerNode prev;
        private WheelTimerNode next;
        private int times;
        private final long delay;
        private final Runnable runnable;

        private WheelTimerNode(int times, long delay, Runnable runnable) {
            this.times = times;
            this.delay = delay;
            this.runnable = runnable;
        }
    }
}
